<template>
    <view>
        <view style="background-color: white; padding: 10px">
            <view style="width: 200px; height: 100px; border: 1px #F3F3F3 solid; margin: 0px auto">
                <uni-file-picker v-model="img_display" fileMediatype="image" mode="grid" limit="1" @select="selectImgDisplay" @progress="progress" @success="success" @fail="fail" @delete="deleteImgDisplay"
                    :image-styles="imageDisplayStyles" />
            </view>
        </view>
        <view style="margin: 10px">
            <button @click="upload" :style="{backgroundColor: theme.color}" style="color: white">上传</button>
        </view>
    </view>
</template>

<script>
import { url, asset } from '@/common/js/url'
import uniFilePicker from '@/components/uni-ui/uni-file-picker/uni-file-picker'

export default {
    components: { uniFilePicker },
    data() {
        return {
            theme: {},
            img_display: [],
            img_display_tmp: '',
            imageDisplayStyles: {
                width: 200,
                height: 100
            }
        }
    },
    created() {
        this.theme = {
            color: 'red'
        }
    },
    methods: {
        selectImgDisplay(e) {
            this.img_display_tmp = e.tempFilePaths[0]
        },
        deleteImgDisplay(e) {
            this.img_display = []
            this.img_display_tmp = ''
        },
        upload() {
            if (this.img_display_tmp == '') {
                uni.showModal({
                    content: '请选择图片',
                    showCancel: false
                })
            } else {
                uni.uploadFile({
                    url: url('/api/upload/image'), //仅为示例，非真实的接口地址
                    filePath: this.img_display_tmp,
                    fileType: "image",  //支付宝小程序必填
                    name: 'file',
                    formData: {
                        'field': 'img'
                    },
                    success: (uploadFileRes) => {
                        console.log(uploadFileRes)
                        const result = JSON.parse(uploadFileRes.data)
                        this.img_display = [{
                            url: asset(result.data.file_name),
                            file_name: result.data.file_name
                        }]
                        this.img_display_tmp = ''
                        uni.showModal({
                            content: '上传成功',
                            showCancel: false
                        })
                    }
                });
            }
        }
    }
}
</script>

<style scoped lang="scss">
</style>